package com.ujs.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ujs.eduservice.entity.EduCourse;
import com.ujs.eduservice.entity.EduCourseDescription;
import com.ujs.eduservice.entity.EduTeacher;
import com.ujs.eduservice.entity.vo.CourseInfoVo;
import com.ujs.eduservice.entity.vo.CoursePublishVo;
import com.ujs.eduservice.entity.vo.CourseQueryVo;
import com.ujs.eduservice.entity.vo.CourseReturnVo;
import com.ujs.eduservice.entity.vo.frontVo.CourseFrontVo;
import com.ujs.eduservice.entity.vo.frontVo.CourseWebVo;
import com.ujs.eduservice.mapper.EduCourseMapper;
import com.ujs.eduservice.service.*;
import com.ujs.servicebase.entity.CourseVoOrder;
import com.ujs.servicebase.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-08-07
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {
    @Autowired
    private EduCourseDescriptionService courseDescriptionService;
    @Autowired
    private EduTeacherService eduTeacherService;
    @Autowired
    private EduChapterService chapterService;
    @Autowired
    private EduVideoService videoService;

    @Override
    @Transactional
    public String saveCourseInfo(CourseInfoVo vo) {
        // 1.向课程表添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(vo, eduCourse);
        try {
            baseMapper.insert(eduCourse);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "添加课程基本信息失败");
        }
        // 2.向课程简介表添加课程简介
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(vo.getDescription());
        courseDescription.setId(eduCourse.getId());
        try {
            courseDescriptionService.save(courseDescription);
            return eduCourse.getId();
        } catch (Exception e) {
            throw new GuliException(20001, "添加课程描述信息失败");
        }
    }

    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        EduCourse eduCourse = baseMapper.selectById(courseId);
        if (eduCourse != null) {
            // 设置基本信息
            BeanUtils.copyProperties(eduCourse, courseInfoVo);
            // 设置描述信息
            EduCourseDescription eduCourseDescription = courseDescriptionService.getById(eduCourse.getId());
            if (eduCourseDescription != null) {
                courseInfoVo.setDescription(eduCourseDescription.getDescription());
                return courseInfoVo;
            } else {
                throw new GuliException(20001, "数据库不存在该课程的描述");
            }
        } else {
            throw new GuliException(20001, "数据库不存在该课程");
        }
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        // 修改基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);

        // 修改描述信息
        EduCourseDescription courseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVo, courseDescription);

        // 更新
        int update = baseMapper.updateById(eduCourse);
        if (update == 0) {
            throw new GuliException(20001, "修改课程信息失败");
        }
        boolean b = courseDescriptionService.updateById(courseDescription);
        if (!b) {
            throw new GuliException(20001, "修改课程描述信息失败");
        }
    }

    @Override
    public CoursePublishVo getPublishCourseInfo(String courseId) {
        return baseMapper.getPublishCourseInfo(courseId);
    }

    @Override
    public Map<String, Object> getCourseList(Long current, Long size, CourseQueryVo courseQueryVo) {
        IPage<EduCourse> page = new Page<>(current, size);
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQueryVo.getTitle())) {
            queryWrapper.like("title", courseQueryVo.getTitle());
        }
        if (!StringUtils.isEmpty(courseQueryVo.getBegin())) {
            queryWrapper.ge("gmt_create", courseQueryVo.getBegin());
        }
        if (!StringUtils.isEmpty(courseQueryVo.getEnd())) {
            queryWrapper.le("gmt_create", courseQueryVo.getEnd());
        }
        // 查询到讲师的id
        if (!StringUtils.isEmpty(courseQueryVo.getTeacherId())) {
            queryWrapper.eq("teacher_id", courseQueryVo.getTeacherId());
        }
        if (!StringUtils.isEmpty(courseQueryVo.getStatus())) {
            queryWrapper.eq("status", courseQueryVo.getStatus());
        }
        queryWrapper.orderByDesc("gmt_modified");
        IPage<EduCourse> eduCourseIPage = baseMapper.selectPage(page, queryWrapper);
        List<EduCourse> records = eduCourseIPage.getRecords();
        // 把讲师id更改为讲师姓名
        List<CourseReturnVo> collect = records.stream().map(record -> {
            CourseReturnVo courseReturnVo = new CourseReturnVo();
            BeanUtils.copyProperties(record, courseReturnVo);
            String teacherId = record.getTeacherId();
            EduTeacher teacher = eduTeacherService.getById(teacherId);
            courseReturnVo.setTeacherName(teacher.getName());
            return courseReturnVo;
        }).collect(Collectors.toList());

        HashMap<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("rows", collect);
        return map;
    }

    /**
     * 删除课程，同时删除课程描述、章节、小节、视频
     *
     * @param courseId 课程id
     */
    @Override
    @Transactional
    public void deleteCourseAllInfo(String courseId) {
        // 1. 删除小节
        videoService.removeVideoByCourseId(courseId);
        // 2. 删除章节
        chapterService.removeChapterByCourseId(courseId);
        // 3. 删除描述
        try {
            courseDescriptionService.removeById(courseId);
        } catch (Exception e) {
            throw new GuliException(20001, "删除描述失败");
        }
        // 4. 删除课程
        try {
            baseMapper.deleteById(courseId);
        } catch (Exception e) {
            throw new GuliException(20001, "删除课程失败");
        }
    }

    @Override
    @Cacheable(value = "index", key = "'hotCourse'")
    public List<EduCourse> getHotCourse() {
        QueryWrapper<EduCourse> courseWrapper = new QueryWrapper<EduCourse>().orderByDesc("view_count").last("limit 8");
        return baseMapper.selectList(courseWrapper);
    }

    @Override
    public Map<String, Object> getFrontCourseList(CourseFrontVo courseFrontVo, Page<EduCourse> eduCoursePage) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) {
            wrapper.eq("subject_parent_id", courseFrontVo.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectId())) {
            wrapper.eq("subject_id", courseFrontVo.getSubjectId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) {
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) {
            wrapper.orderByDesc("gmt_create");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {
            wrapper.orderByDesc("price");
        }
        baseMapper.selectPage(eduCoursePage, wrapper);
        List<EduCourse> records = eduCoursePage.getRecords();
        long current = eduCoursePage.getCurrent();
        long pages = eduCoursePage.getPages();
        long size = eduCoursePage.getSize();
        long total = eduCoursePage.getTotal();
        boolean hasNext = eduCoursePage.hasNext();// 下一页
        boolean hasPrevious = eduCoursePage.hasPrevious();// 上一页

        // 把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        // map返回
        return map;
    }

    @Override
    public CourseWebVo getCourseBaseInfo(String courseId) {

        return baseMapper.getCourseBaseInfo(courseId);
    }

    @Override
    public CourseVoOrder getCourseInfoById(String courseId) {
        CourseVoOrder courseVoOrder = new CourseVoOrder();
        EduCourse eduCourse = baseMapper.selectById(courseId);
        courseVoOrder.setCourseCover(eduCourse.getCover());
        courseVoOrder.setCourseTitle(eduCourse.getTitle());
        courseVoOrder.setPrice(eduCourse.getPrice());
        EduTeacher teacher = eduTeacherService.getById(eduCourse.getTeacherId());
        courseVoOrder.setTeacherName(teacher.getName());
        courseVoOrder.setCourseId(eduCourse.getId());
        return courseVoOrder;
    }
}
